package com.sharedprint.system.goods.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sharedprint.dics.service.DicsInfoService;
import com.sharedprint.system.category.pojo.CategoryInfo;
import com.sharedprint.system.category.service.CategoryInfoService;
import com.sharedprint.system.goods.pojo.GoodsInfo;
import com.sharedprint.system.goods.service.GoodsInfoService;
import com.sharedprint.system.user.pojo.UserInfo;
import com.sharedprint.util.RandomCode;

/**
 * 商品信息管理
 */
@Controller
@RequestMapping("/api/info")
public class GoodsInfoController {
	private static final Logger logger = Logger.getLogger("CategoryInfoController");
	@Autowired
	private GoodsInfoService goodsInfoService;
	@Autowired
	private DicsInfoService dicsInfoService;

	
	/**
	 * 云打印商城通过分类id品牌商品名称获取获取商品列表数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryInfos")
	@ResponseBody
	public Map<String, Object> queryMenuLists(HttpServletRequest req) {
		String goodsCategory = req.getParameter("GoodsCategory");
		String goodsBrand = req.getParameter("GoodsBrand");
		String goodsNameLike = req.getParameter("GoodsNameLike");

		System.err.println("goodsCategory="+goodsCategory+"goodsBrand="+goodsBrand+"goodsNameLike="+goodsNameLike);
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		List<Map<String, Object>> categoryList = new ArrayList<Map<String, Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int totalCount = 0;
		if (token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();

			
			int cateCount = 0;
			int brandCount = 0;
			int nameLikeCount = 0;
			//判断商品类别，商品品牌，是否为空
			if (goodsCategory != null && !"".equals(goodsCategory.trim())) {
				searchMap.put("GoodsCategory", goodsCategory);
				cateCount = goodsInfoService.findCateGoodsCount(searchMap);// 商品类别总记录数
				System.err.println("cateCount="+cateCount);
			}
			if (goodsBrand != null && !"".equals(goodsBrand.trim())) {
				searchMap.put("GoodsBrand", goodsBrand);
				brandCount = goodsInfoService.findBrandGoodsCount(searchMap);// 商品类别总记录数
			}
			if(goodsNameLike != null && !"".equals(goodsNameLike.trim()) && goodsNameLike != "null" && !"null".equals(goodsNameLike.trim()))
			{
				searchMap.put("GoodsNameLike", goodsNameLike);
				nameLikeCount = goodsInfoService.findNameLikeGoodsCount(searchMap);
			}
			if (cateCount > 0) {
				categoryList = goodsInfoService.findCateGoodsList(searchMap);
				resultMap.put("pageTotal", totalCount);
				resultMap.put("pageList", categoryList);
				resultMap.put("success", "1");
			}
			else if (brandCount >0) {
				categoryList = goodsInfoService.findBrandGoodsList(searchMap);
				resultMap.put("pageTotal", totalCount);
				resultMap.put("pageList", categoryList);
				resultMap.put("success", "1");
			}
			else if (nameLikeCount > 0) {
				categoryList = goodsInfoService.findGoodsNameLikeList(searchMap);
				resultMap.put("pageTotal", totalCount);
				resultMap.put("pageList", categoryList);
				resultMap.put("success", "1");
			}
			else {
				resultMap.put("success", "0");
			}
		}
		
		

		return resultMap;
	}
	
	/**
	 * 获取商品列表数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryInfo")
	@ResponseBody
	public Map<String, Object> queryMenuList(HttpServletRequest req) {
		String goodsCategory = req.getParameter("GoodsCategory");
		String goodsBrand = req.getParameter("GoodsBrand");
		String minGoodsPrice = req.getParameter("MinGoodsPrice");
		String maxGoodsPrice = req.getParameter("MaxGoodsPrice");
		String goodsNameLike = req.getParameter("GoodsNameLike");
		String goodsId = req.getParameter("goodsId");
		System.err.println("商品goodsId="+goodsId);
		

		String currentPage = req.getParameter("currentPage");
		String pageSize = req.getParameter("pageSize");
		String orderByValue = req.getParameter("orderByValue");
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		String merInfId = req.getHeader("merInfId");
		List<Map<String, Object>> categoryList = new ArrayList<Map<String, Object>>();
		int totalCount = 0;
		if (token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim())) {
			if (currentPage == null || "".equals(currentPage.trim())) {
				currentPage = "0";
			}
			if (pageSize == null || "".equals(pageSize.trim())) {
				pageSize = "10";
			}
			Map<String, Object> searchMap = new HashMap<String, Object>();
			int currentpages = 0;
			if ((currentPage != null || !"".equals(currentPage.trim()))) {
				currentpages = Integer.parseInt(currentPage);
				currentpages = currentpages * Integer.parseInt(pageSize);
			}

			searchMap.put("currentPage", currentpages);
			searchMap.put("pageSize", Integer.parseInt(pageSize));
			searchMap.put("GoodsCategory", goodsCategory);
			searchMap.put("GoodsBrand", goodsBrand);
			if (minGoodsPrice != null && maxGoodsPrice != null) {
				searchMap.put("MinGoodsPrice", Double.parseDouble(minGoodsPrice));
				searchMap.put("MaxGoodsPrice", Double.parseDouble(maxGoodsPrice));
			}
            searchMap.put("goodsId", goodsId);
			searchMap.put("GoodsNameLike", goodsNameLike);
			searchMap.put("merInfId", merInfId);
			totalCount = goodsInfoService.findGoodsInfoCount(searchMap);// 总记录数
			if (totalCount > 0) {
				if (orderByValue == null || "".equals(orderByValue.trim())) {
					searchMap.put("orderByAreaIdDesc", "1");
				}
				categoryList = goodsInfoService.findGoodsInfoList(searchMap);
			}
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("currentPage", Integer.parseInt(currentPage) + 1);
		resultMap.put("pageTotal", totalCount);
		resultMap.put("pageList", categoryList);
		resultMap.put("success", "1");

		return resultMap;
	}

	/**
	 * 验证类别名称
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/validGoodsName")
	@ResponseBody
	public boolean validGoodsName(HttpServletRequest req) {
		String goodsName = req.getParameter("addGoodsName");
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		// logger.info("catId=" + catId + ",token=" + token + ",userId=" + userId +
		// ",categoryName=" + categoryName);
		boolean result = false;
		if (goodsName != null && !"".equals(goodsName.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("goodsName", goodsName);
			int count = goodsInfoService.findGoodsInfoCount(searchMap);
			if (count == 0) {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 保存商品信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/add")

	@ResponseBody
	public Map<String, Object> add(HttpServletRequest req) {
		String addGoodsName = req.getParameter("addGoodsName");
		String addParentBrand = req.getParameter("addParentBrand");
		String addParentCategory = req.getParameter("addParentCategory");
		String addPrice = req.getParameter("addPrice");
		BigDecimal price = new BigDecimal(addPrice);
		String addSortNo = req.getParameter("addSortNo");
		String addGoodsDescription = req.getParameter("addGoodsDescription");
		String addMaterial1 = req.getParameter("addMaterial1");
		String addMaterial2 = req.getParameter("addMaterial2");
		String addMaterial3 = req.getParameter("addMaterial3");
		String addMaterial4 = req.getParameter("addMaterial4");
		String addMaterial5 = req.getParameter("addMaterial5");
		String addMaterial6 = req.getParameter("addMaterial6");
		RandomCode code=new RandomCode();
		String goodsCode=code.getRandomCode();

		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		String merInfId = req.getHeader("merInfId");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (addPrice != null && !"".equals(addPrice.trim()) && addGoodsName != null && !"".equals(addGoodsName.trim())
				&& addSortNo != null && !"".equals(addSortNo.trim()) && addParentBrand != null
				&& !"".equals(addParentBrand.trim()) && addParentCategory != null
				&& !"".equals(addParentCategory.trim()) && token != null && !"".equals(token.trim()) && userId != null
				&& !"".equals(userId.trim())) {
             
			GoodsInfo goodsInfo = new GoodsInfo();
			goodsInfo.setGoodsCode(goodsCode);
			goodsInfo.setGoodsName(addGoodsName);
			goodsInfo.setCategoryId(Integer.parseInt(addParentBrand));
			goodsInfo.setBrandId(Integer.parseInt(addParentCategory));
			goodsInfo.setPrice(price);
			goodsInfo.setRemark(addGoodsDescription);
			goodsInfo.setSortNo(Integer.parseInt(addSortNo));
			goodsInfo.setOprId(Integer.parseInt(userId));
			goodsInfo.setMerinfId(Integer.parseInt(merInfId));
			goodsInfo.setPicture1(addMaterial1);
			goodsInfo.setPicture2(addMaterial2);
			goodsInfo.setPicture3(addMaterial3);
			goodsInfo.setPicture4(addMaterial4);
			goodsInfo.setPicture5(addMaterial5);
			goodsInfo.setPicture6(addMaterial6);
			try {
				int success = goodsInfoService.saveInfo(goodsInfo);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "保存失败");
				}
			} catch (Exception e) { // logger.info("保存异常=" + e.getMessage());
				e.printStackTrace();
				resultMap.put("msg", "保存异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}
	/**
	 * 获取修改相关信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/initUpdate")
	@ResponseBody
	public Map<String, Object> initUpdate(HttpServletRequest req) {
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		String updategoodsId = req.getParameter("updategoodsId");
		//logger.info("token=" + token + ",userId=" + userId + ",updateCategoryId=" + updateCategoryId);

		Map<String, Object> goodsMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		if (token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim()) && userId != null
				&& !"".equals(userId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("goodsId", updategoodsId);
			goodsList = goodsInfoService.findGoodsInfoList(searchMap);
			goodsMap = goodsList.get(0);
			goodsList = goodsInfoService.findGoodsInfoList(null);
		}
		resultMap.put("goodsList", goodsList);
		resultMap.put("goodsMap", goodsMap);
		resultMap.put("success", "1");
		return resultMap;
	}
	/**
	 * 修改信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Map<String, Object> update(HttpServletRequest req) {
		String goodsId = req.getParameter("updateGoodsId");
		String updateParentBrand = req.getParameter("updateParentBrand");
		String updateParentCategory = req.getParameter("updateParentCategory");
		String updatePrice = req.getParameter("updatePrice");
		BigDecimal price = new BigDecimal(updatePrice);
		String updateSortNo = req.getParameter("updateSortNo");
		String updateGoodsDescription = req.getParameter("updateGoodsDescription");
		String updateMaterial1 = req.getParameter("updateMaterial1");
		String updateMaterial2 = req.getParameter("updateMaterial2");
		String updateMaterial3 = req.getParameter("updateMaterial3");
		String updateMaterial4 = req.getParameter("updateMaterial4");
		String updateMaterial5 = req.getParameter("updateMaterial5");
		String updateMaterial6 = req.getParameter("updateMaterial6");
		
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		String merInfId = req.getHeader("merInfId");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");

		if (updateParentBrand != null && !"".equals(updateParentBrand.trim()) && updateParentCategory != null
				&& !"".equals(updateParentCategory.trim()) && updatePrice != null
				&& !"".equals(updatePrice.trim())) {
			GoodsInfo goodsInfo = new GoodsInfo();
			goodsInfo.setGoodsId(Integer.parseInt(goodsId));
			goodsInfo.setCategoryId(Integer.parseInt(updateParentBrand));
			goodsInfo.setBrandId(Integer.parseInt(updateParentCategory));
			goodsInfo.setPrice(price);
			goodsInfo.setRemark(updateGoodsDescription);
			goodsInfo.setSortNo(Integer.parseInt(updateSortNo));
			goodsInfo.setOprId(Integer.parseInt(userId));
			goodsInfo.setMerinfId(Integer.parseInt(merInfId));
			goodsInfo.setPicture1(updateMaterial1);
			goodsInfo.setPicture2(updateMaterial2);
			goodsInfo.setPicture3(updateMaterial3);
			goodsInfo.setPicture4(updateMaterial4);
			goodsInfo.setPicture5(updateMaterial5);
			goodsInfo.setPicture6(updateMaterial6);
			try {
				int success = goodsInfoService.updateInfo(goodsInfo);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "修改失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("修改异常=" + e.getMessage());
				resultMap.put("msg", "修改异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}
	// 删除前台商品数据
	@RequestMapping("/deleteGoods")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest req, HttpServletResponse resp)  {
		String goodsId = req.getParameter("goodsId");
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (goodsId != null && !"".equals(goodsId.trim()) && token != null && !"".equals(token.trim()) && userId != null
				&& !"".equals(userId.trim())) {
			 //判断是否有下级
			int success = goodsInfoService.delGoods(Integer.parseInt(goodsId));
			if (success > 0) {
				resultMap.put("success", "1");
			} else {
				resultMap.put("msg", "该菜单存在子菜单,不允许删除!");
			}
		}
		return resultMap;
	}
	/**
	 * 前台商品信息详情
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/detailInfo")

	@ResponseBody
	public Map<String, Object> detailFront(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		String goodsId = req.getParameter("goodsId");

		Map<String, Object> goodsMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		if (token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("goodsId", goodsId);
			goodsList = goodsInfoService.findGoodsInfoList(searchMap);
			goodsMap = goodsList.get(0);
		}
		resultMap.put("goodsMap", goodsMap);
		resultMap.put("success", "1");
		return resultMap;

	}

	/**
	 * 审核信息
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/checkInfo")
	@ResponseBody
	public Map<String, Object> checkInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		String goodsId = req.getParameter("goodsId");

		Map<String, Object> goodsMap = new HashMap<String, Object>();
		Map<String, Object> checkMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> checkInfoList = new ArrayList<Map<String, Object>>();
		if (token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("goodsId", goodsId);
			goodsList = goodsInfoService.findGoodsInfoList(searchMap);
			goodsMap = goodsList.get(0);

			// 获取审核状态下拉框
			checkMap.put("dicsCode", "checkStatus");
			checkInfoList = dicsInfoService.findDicsList(checkMap);
		}
		resultMap.put("checkInfoList", checkInfoList);
		resultMap.put("goodsMap", goodsMap);
		resultMap.put("success", "1");
		return resultMap;

	}

	/**
	 * 提交审核信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/upcheckInfo")
	@ResponseBody
	public Map<String, Object> upcheckInfo(HttpServletRequest req) {
		String checkAdvise = req.getParameter("checkAdvise");
		String checkStatus = req.getParameter("checkStatus");
		String goodsCode = req.getParameter("GoodsCode");

		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (checkAdvise != null && !"".equals(checkAdvise.trim()) && checkStatus != null
				&& !"".equals(checkStatus.trim()) && token != null && !"".equals(token.trim()) && userId != null
				&& !"".equals(userId.trim())) {

			GoodsInfo goodsInfo = new GoodsInfo();
			goodsInfo.setCheckAdvise(checkAdvise);
			goodsInfo.setCheckStatus(Integer.parseInt(checkStatus));
			goodsInfo.setCheckMan(userId);
			goodsInfo.setGoodsCode(goodsCode);
			try {
				int success = goodsInfoService.upcheckInfo(goodsInfo);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "提交失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				resultMap.put("msg", "提交异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}
}
